package com.lagou;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class ConsumerMain {

    public static void main(String[] args) throws Exception {
        /**
         * 测试fanout
         */
        testFanoutExchange();
    }

    public static void testFanoutExchange() throws Exception {
        //连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri("amqp://guest:guest@localhost:5672/%2f");
        //创建连接
        Connection connection = connectionFactory.newConnection();
        //创建通道
        Channel channel1 = connection.createChannel();
        Channel channel2 = connection.createChannel();
        /**
         * 消费者端重复定义交换器可以确保队列绑定之前交换器是存在的，要求参数完全一致，否则报错
         */
        channel1.exchangeDeclare("MyFanoutExchange", BuiltinExchangeType.FANOUT, true, true, null);

        /**
         * 使用broker生成的队列名称
         */
        String queueName = channel1.queueDeclare().getQueue();

        /**
         * 绑定交换器和队列，无需命名绑定键
         */
        channel1.queueBind(queueName, "MyFanoutExchange", "");

        /**
         * 订阅queueName并设置回调函数
         */
        channel1.basicConsume(queueName, (consumerTag, message) -> {
            System.out.println("channel1:" + queueName + ":" + new String(message.getBody()));
        }, consumerTag -> {
        });
        /**
         * 订阅queueName并设置回调函数
         */
        channel2.basicConsume(queueName, (consumerTag, message) -> {
            System.out.println("channel2:" + queueName + ":" + new String(message.getBody()));
        }, consumerTag -> {
        });
    }

}
